#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/ip.h>
#include <fcntl.h>
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
    int fd_s = socket(PF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(-1, fd_s, "socket");
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(fd_s,(void*)&saddr,sizeof saddr);
    ERROR_CHECK(-1,ret,"connect");
    puts("connected!");
    char buf[1024];
    int fd_file = open("qwe.png", O_CREAT|O_WRONLY|O_TRUNC,0777);
    ERROR_CHECK(-1, fd_file, "open");
    int count;
    char p_len[5];
    int len ;
    while (1)
    {
        ret = read(fd_s,p_len,5);
        if (ret == 0)
        {
            break;
        }else if(ret == -1){
            perror("read");
            break;
        }
        len = atoi(p_len);
        if (0 == len)
        {
            break;
        }
        count = 0;
        while (count <len)
        {
            ret = read(fd_s,buf+count,len - count);
            count += ret;
        }
        write(fd_file,buf,len);
        
        
        
    }
    
    return 0;
}
